var cmbArea = '';
var addressInit = function(_cmbProvince, _cmbCity, _cmbArea, _cmbStreet, defaultProvince, defaultCity, defaultArea, defaultStreet) {

    var cmbProvince = document.getElementById(_cmbProvince);
    var cmbCity = document.getElementById(_cmbCity);
    cmbArea = document.getElementById(_cmbArea);
    var cmbStreet = document.getElementById(_cmbStreet);

    function cmbSelect(cmb, str) { //返回当前显示的index
        for (var i = 0; i < cmb.options.length; i++) {
            if (cmb.options[i].value == str) {
                cmb.selectedIndex = i;
                if (cmb == cmbArea) {
                    console.log(cmbArea);
                    return cmb.selectedIndex;
                }
                return;
            }
        }

    }

    function cmbAddOption(cmb, str, obj) { //添加每一个option的具体的属性...
        var option = document.createElement("option");
        cmb.options.add(option);
        option.innerText = str;
        option.value = str;
        option.obj = obj;
    }

    function changeCity() { //
        cmbArea.options.length = 0; //清空该项下的option
        if (cmbCity.selectedIndex == -1) return;
        var item = cmbCity.options[cmbCity.selectedIndex].obj;
        for (var i = 0; i < item.district.length; i++) {
            cmbAddOption(cmbArea, item.district[i].name, item.district[i]); //添加的对象为null，？
        }
        cmbSelect(cmbArea, defaultArea);

        item = cmbArea.options[cmbArea.selectedIndex].obj;
        console.log(item);
        $("#state").val(item.state_code);
        $("#city").val(item.city_code);
        $("#district").val(item.district_code);
    }

    function changeProvince() {
        cmbCity.options.length = 0;
        cmbCity.onchange = null;
        if (cmbProvince.selectedIndex == -1) return;
        var item = cmbProvince.options[cmbProvince.selectedIndex].obj;
        for (var i = 0; i < item.city.length; i++) { //
            cmbAddOption(cmbCity, item.city[i].name, item.city[i]); //
        }
        cmbSelect(cmbCity, defaultCity);
        changeCity();
        cmbCity.onchange = changeCity;
    }

    for (var i = 0; i < provinceList.length; i++) {
        cmbAddOption(cmbProvince, provinceList[i].name, provinceList[i]);
    }
    cmbSelect(cmbProvince, defaultProvince);
    changeProvince();

    cmbProvince.onchange = changeProvince;
    cmbArea.onchange = function() {
        if (cmbArea.selectedIndex == -1) return;
        var item = cmbArea.options[cmbArea.selectedIndex].obj;
        console.log(item);
        $("#state").val(item.state_code);
        $("#city").val(item.city_code);
        $("#district").val(item.district_code);
    }
}